package com.wenming.crashcachedemo;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.wanjian.cockroach.ExceptionHandler;
import com.wenming.crashcachedemo.support.CrashLog;
import com.wenming.crashcachedemo.support.DebugSafeModeTipActivity;
import com.wenming.library.LogReport;
import com.wenming.library.save.imp.CrashWriter;
import com.wenming.library.upload.email.EmailReporter;


/**
 * Created by wenmingvs on 2016/7/4.
 */
public class App extends Application {

    private String TAG = App.class.getSimpleName();
    private Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        initCrashReport();
    }

    private void initCrashReport() {
        LogReport.getInstance()
                .setCacheSize(30 * 1024 * 1024)//支持设置缓存大小，超出后清空
                .setLogDir(getApplicationContext(), Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + "/" + this.getString(this.getApplicationInfo()
                        .labelRes) + "/")//定义路径为：sdcard/[app name]/
                .setWifiOnly(false)//设置只在Wifi状态下上传，设置为false为Wifi和移动网络都上传
                .setLogSaver(new CrashWriter(getApplicationContext()))//支持自定义保存崩溃信息的样式
                //.setEncryption(new AESEncode()) //支持日志到AES加密或者DES加密，默认不开启
                .init(getApplicationContext(), mExceptionHandler);
        initEmailReporterQQ();
        //设置全局上传
        LogReport.getInstance().upload(this);
    }

    ExceptionHandler mExceptionHandler = new ExceptionHandler() {
        @Override
        protected void onUncaughtExceptionHappened(Thread thread, Throwable throwable) {
            Log.e(TAG, "--->onUncaughtExceptionHappened:" + thread + "<---");
            CrashLog.saveCrashLog(getApplicationContext(), throwable);
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
//                                toast.setText(R.string.safe_mode_excep_tips);
//                                toast.show();
//                                Toast.makeText(context,"")

                    if (BuildConfig.DEBUG) {
                        Toast.makeText(getApplicationContext(), "onUncaughtExceptionHappened", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        @Override
        protected void onBandageExceptionHappened(Throwable throwable) {
            throwable.printStackTrace();//打印警告级别log，该throwable可能是最开始的bug导致的，无需关心
//                        toast.setText("Cockroach Worked");
//                        toast.show();
            Log.e(TAG, "--->onBandageExceptionHappened:" + "<---");
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    if (BuildConfig.DEBUG) {
                        Toast.makeText(getApplicationContext(), "onUncaughtExceptionHappened", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        @Override
        protected void onEnterSafeMode() {
//                        int tips = R.string.safe_mode_tips;
//                        Toast.makeText(App.this, getResources().getString(tips), Toast.LENGTH_LONG).show();
//                        DebugSafeModeUI.showSafeModeUI();

            Log.e(TAG, "--->onEnterSafeMode:" + "<---");
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    if (BuildConfig.DEBUG) {
                        Intent intent = new Intent(App.this, DebugSafeModeTipActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(getApplicationContext(), "onEnterSafeMode", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        @Override
        protected void onMayBeBlackScreen(Throwable e) {
            Thread thread = Looper.getMainLooper().getThread();
            Log.e(TAG, "--->onMayBeBlackScreen:" + thread + "<---");
            //黑屏时建议直接杀死app  ?
            final Thread.UncaughtExceptionHandler sysExcepHandler =
                    Thread.getDefaultUncaughtExceptionHandler();
            sysExcepHandler.uncaughtException(thread, new RuntimeException("black screen"));
        }

    };

    /**
     * 使用QQ EMAIL发送日志
     */
    private void initEmailReporterQQ() {
        EmailReporter email = new EmailReporter(this);
        email.setReceiver("2559632361@qq.com");//收件人
        email.setSender("226125623@qq.com");//发送人邮箱
        email.setSendPassword("yxwrdqldgfisbhef");//邮箱的客户端授权码，注意不是邮箱密码
        email.setSMTPHost("smtp.qq.com");//SMTP地址
        email.setPort("465");//SMTP 端口
        LogReport.getInstance().setUploadType(email);
    }


    /**
     * 使用EMAIL发送日志 Outlook测试失败， 可能是加密方式错误。
     */
    private void initEmailReporterOutlook() {
        EmailReporter email = new EmailReporter(this);
        email.setReceiver("602073555@qq.com");//收件人
        email.setSender("AdasSwift@outlook.com");//发送人邮箱
        email.setSendPassword("outlookMM011416");//邮箱的客户端授权码，注意不是邮箱密码
        email.setSMTPHost("smtp-mail.outlook.com");//SMTP地址
        email.setPort("587");//SMTP 端口
//        LogReport.getInstance().setEncryption();
        LogReport.getInstance().setUploadType(email);
        Log.d(TAG, "initEmailReporterOutlook: b");
    }


}
